﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;
using Fayshine.VA.Models;
using Visifire.Charts;
using Fayshine.VA.Helpers;

namespace Fayshine.VA.Views.SearchStatistics
{
    public partial class AnyDurationPassengerCompare : Page
    {
        private SearchStatisticsViewModel m_ViewModel;

        public AnyDurationPassengerCompare()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(AnyDurationPassengerCompare_Loaded);
        }

        #region Event Methods

        private void AnyDurationPassengerCompare_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;
            this.endDatePicker.SelectedDate = DateTime.Now;

            this.startDatePicker2.SelectedDate = DateTime.Now;
            this.endDatePicker2.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn,
                                                            List<HistoryPassengerFlow> firstHistoryPassengerFlow,
                                                            List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
             {
                 vcChart.AxesX.Clear();

                 Axis xAxis = new Axis();
                 DateTime minDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Min();
                 DateTime maxDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Max();
                 xAxis.AxisMinimum = minDateTime;
                 xAxis.AxisMaximum = maxDateTime;
                 xAxis.ValueFormatString = "HH:mm";
                 xAxis.IntervalType = IntervalTypes.Hours;
                 xAxis.Interval = 1;
                 vcChart.AxesX.Add(xAxis);

                 string[] titleArr = title.Split(new char[] { ',' });
                 RenderAs type = cmbStyle.SelectedIndex == 0 ? RenderAs.Line : RenderAs.Column;
                 DataSeries series = ChartHelper.GetDataSeries(type, titleArr[0], ChartValueTypes.Time);
                 series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                 string title1 = "进";
                 string path = "InCount";
                 if (cmbInorOut.SelectedIndex == 1)
                 {
                     path = "OutCount";
                     title1 = "出";
                 }
                 else if (cmbInorOut.SelectedIndex == 2)
                 {
                     title1 = "滞留";
                     path = "StrandedCount";
                 }

                 Title vcChart1Title = new Visifire.Charts.Title();
                 vcChart1Title.Text = "任意时段客流分布对比图(" + title1 + ")";
                 vcChart.Titles.Add(vcChart1Title);

                 series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
                 series.DataSource = firstHistoryPassengerFlow;
                 vcChart.Series.Add(series);

                 DataSeries series2 = ChartHelper.GetDataSeries(type, titleArr[1], ChartValueTypes.Time);
                 series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                 series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
                 series2.DataSource = secondHistoryPassengerFlow;
                 vcChart.Series.Add(series2);

                 LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                 indicator.IsBusy = false;
             });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart != null)
                {
                    vcChart.AxesX.Clear();
                    vcChart.TrendLines.Clear();
                    vcChart.Series.Clear();
                    vcChart.Titles.Clear();
                }
            });
        }

        private void cmbAreas1_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbArea1ItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger1.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger1.IsEnabled = true;
                    }

                }
                else
                {
                    cbArea1ItemDisplay.Content = string.Empty;
                }
                cmbAreas1.SelectedItem = null;
                cmbAreas1.SelectedItem = cbArea1ItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
                cmbPassenger1_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger1_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cbPassengerItemDisplay.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cbPassengerItemDisplay.Content = string.Empty;
                }
                cmbPassenger1.SelectedItem = null;
                cmbPassenger1.SelectedItem = cbPassengerItemDisplay;
            }
        }

        private void cmbAreas2_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends2.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbArea2ItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger2.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger2.IsEnabled = true;
                    }

                }
                else
                {
                    cbArea2ItemDisplay.Content = string.Empty;
                }
                cmbAreas2.SelectedItem = null;
                cmbAreas2.SelectedItem = cbArea2ItemDisplay;

                m_ViewModel.SelectAreasChanged2(selectedArea);
                cmbPassenger2_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger2_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts2.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cmbPassenger2ItemDisplay.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cmbPassenger2ItemDisplay.Content = string.Empty;
                }
                cmbPassenger2.SelectedItem = null;
                cmbPassenger2.SelectedItem = cmbPassenger2ItemDisplay;
            }
        }


        #endregion

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (!m_ViewModel.IsConditionSelected2())
            {
                MessageBox.Show("请选择店铺或者门面！");
                return;
            }

            DateTime startTime1 = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                               startDatePicker.SelectedDate.Value.Month,
                                               startDatePicker.SelectedDate.Value.Day,
                                               0, 0, 0);
            DateTime endTime1 = new DateTime(endDatePicker.SelectedDate.Value.Year,
                                                endDatePicker.SelectedDate.Value.Month,
                                                endDatePicker.SelectedDate.Value.Day,
                                                0, 0, 0);
            endTime1 = endTime1.AddDays(1);
            DateTime startTime2 = new DateTime(startDatePicker2.SelectedDate.Value.Year,
                                              startDatePicker2.SelectedDate.Value.Month,
                                              startDatePicker2.SelectedDate.Value.Day,
                                              0, 0, 0);
            DateTime endTime2 = new DateTime(endDatePicker2.SelectedDate.Value.Year,
                                                endDatePicker2.SelectedDate.Value.Month,
                                                endDatePicker2.SelectedDate.Value.Day,
                                                0, 0, 0);
            endTime2 = endTime2.AddDays(1);

            if (startTime1 > endTime1 || startTime2 > endTime2)
            {
                MessageBox.Show("开始时间不能小于结束时间");
            }
            else
            {
                List<DayOfWeek> enableWeeks1 = new List<DayOfWeek>();
                if (ckb1Week1.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Monday);
                if (ckb1Week2.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Tuesday);
                if (ckb1Week3.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Wednesday);
                if (ckb1Week4.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Thursday);
                if (ckb1Week5.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Friday);
                if (ckb1Week6.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Saturday);
                if (ckb1Week7.IsChecked.Value) enableWeeks1.Add(DayOfWeek.Sunday);

                List<DayOfWeek> enableWeeks2 = new List<DayOfWeek>();
                if (ckb2Week1.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Monday);
                if (ckb2Week2.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Tuesday);
                if (ckb2Week3.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Wednesday);
                if (ckb2Week4.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Thursday);
                if (ckb2Week5.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Friday);
                if (ckb2Week6.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Saturday);
                if (ckb2Week7.IsChecked.Value) enableWeeks2.Add(DayOfWeek.Sunday);

                bool isAvg1 = cmb.SelectedIndex == 0 ? true : false;
                bool isAvg2 = cmb2.SelectedIndex == 0 ? true : false;

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_ViewModel.RefreshAnyDurationPassengerCompare(true,
                                                               startTime1,
                                                               endTime1,
                                                               isAvg1,
                                                               startTime2,
                                                               endTime2,
                                                               isAvg2,
                                                               enableWeeks1,
                                                               enableWeeks2);

            }
            
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
